# -*- coding:UTF-8 -*-
import sys

import requests
from bs4 import BeautifulSoup

"""
类说明:下载《笔趣看》网小说《一念永恒》
Parameters:
    无
Returns:
    无
Modify:
    2019-10-12
"""


class downloader(object):
    def __init__(self):
        self.server = 'http://www.biqukan.com/'
        self.target = 'http://www.biqukan.com/1_1094/'
        self.names = []  # 存放章节名
        self.urls = []  # 存放章节链接
        self.nums = 0  # 章节数

    '''
    获取章节
    '''

    def getChapters(self):
        response = requests.get(self.target)
        html = response.text
        div_bf = BeautifulSoup(html, 'html5lib')
        div = div_bf.find_all('div', class_='listmain')

        a_bf = BeautifulSoup(
            str(div[0]).encode(response.encoding, 'ignore').decode(response.apparent_encoding, 'ignore'), 'html5lib')
        a = a_bf.find_all('a')
        self.nums = len(a[13:])

        for each in a[13:]:
            name = each.string
            url = (self.server + each.get('href'))
            self.names.append(name)
            self.urls.append(url)
        print("获取章节结束, 共" + str(self.nums) + "章")

    '''
    获取内容
    '''

    def getContent(self, target):
        response = requests.get(target)
        dom = BeautifulSoup(response.text, 'html5lib')
        divcontent = dom.find_all('div', id='content')
        content = divcontent[0].text.replace('\xa0' * 8, '')

        return content.encode(response.encoding, 'ignore').decode(response.apparent_encoding, 'ignore')

    '''
    保存文件
    '''

    def saveText(self, name, path, text):
        with open(path, 'a', encoding='utf-8') as f:
            f.write(name + '\n')
            f.writelines(text)
            f.write('\n\n')


if __name__ == '__main__':
    dl = downloader()
    dl.getChapters()
    print('《一年永恒》开始下载：')
    for i in range(dl.nums):
        dl.saveText(dl.names[i], '一念永恒.txt', dl.getContent(dl.urls[i]))
        sys.stdout.write("  已下载:%.3f%%" % float(i / dl.nums) + '\r')
        sys.stdout.flush()
    print('《一年永恒》下载完成')
